package com.briup.MR.Sort.SecondSort;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import java.io.IOException;

/*
yarn jar HdfsClientDemo-1.0-SNAPSHOT.jar com.briup.MR.Sort.SecondSort.SecondSort -D input=/user/hdfs/wea.txt -D output=/user/hdfs/secord_result
 */
public class SecondSort extends Configured implements Tool {
    static class SecondSortMapper extends Mapper<LongWritable, Text,YearTemp, DoubleWritable>{
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String[] strings = value.toString().split(",");
            YearTemp k = new YearTemp(strings[0], Double.parseDouble(strings[1]));
            context.write(k,new DoubleWritable(Double.parseDouble(strings[1])));
        }
    }
    static class SecondSortReduce
            extends Reducer<YearTemp,DoubleWritable,YearTemp,DoubleWritable>{
        @Override
        protected void reduce(YearTemp key, Iterable<DoubleWritable> values, Context context) throws IOException, InterruptedException {
            YearTemp k=
                    new YearTemp(key.getYear(),key.getTemp());
            for(DoubleWritable val:values){
                context.write(k,val);
            }
        }
    }
    public int run(String[] strings) throws Exception {
        Configuration conf=getConf();
        String input=conf.get("input");
        String output=conf.get("output");

        Job job= Job.getInstance(conf);
        job.setJarByClass(this.getClass());
        job.setJobName("SecordSort");

        job.setMapperClass(SecondSortMapper.class);
        job.setMapOutputKeyClass(YearTemp.class);
        job.setMapOutputValueClass(DoubleWritable.class);

        job.setPartitionerClass(SecordPartitioner.class);

        job.setGroupingComparatorClass(
                YearTempGroup.class);
        job.setNumReduceTasks(2);

        job.setReducerClass(SecondSortReduce.class);
        job.setOutputKeyClass(YearTemp.class);
        job.setMapOutputValueClass(DoubleWritable.class);


        TextInputFormat.addInputPath(job,
                new Path(input));
        TextOutputFormat.setOutputPath(job,
                new Path(output));
        return job.waitForCompletion(true)?0:-1;
    }

    public static void main(String[] args) throws Exception {
        System.exit(
                new ToolRunner().run(
                        new SecondSort(),args));
    }
}
